#include "AuthUserDlg.h"
#include "resource.h"
#include "MenuDlg.h"
#include "DatabaseAccess.h"
#include "CardBussiness.h"
#include "ValidateCardDlg.h"
#include "common.h"

LRESULT CALLBACK AuthUserDlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{	
    AuthUserDlg *Obj;
    if (message==WM_INITDIALOG)
    {	
        Obj=(AuthUserDlg*)lParam;
        SetWindowLong(hWnd,GWL_USERDATA,(LONG)Obj);
    }
    Obj=(AuthUserDlg*)GetWindowLong(hWnd,GWL_USERDATA);
    if (Obj)
        return Obj->DialogProc(hWnd, message, wParam, lParam);
    return 0;
}

AuthUserDlg::AuthUserDlg(HINSTANCE hInstance, HWND hParent)
{
    DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DIALOG_AUTH_USER), hParent, (DLGPROC)AuthUserDlgProc, (LPARAM)this);
}

AuthUserDlg::~AuthUserDlg(void)
{
    EndDialog(m_hDlg,0);
}

LRESULT AuthUserDlg::DialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    HWND hEditPIN;
    CCardBussiness objCardBuss;
    char sPINInput[8]; 

    switch (message) 
    {
    case WM_INITDIALOG:
        {	
            hEditPIN = GetDlgItem(hWnd, IDC_EDIT_PIN);
            m_hDlg = hWnd;	
            SetFocus(hEditPIN);
            return FALSE;
        }		
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {	
		case IDOK:
			{     
                hEditPIN = GetDlgItem(hWnd, IDC_EDIT_PIN);
                GetWindowText(hEditPIN, sPINInput, 8);
                int nCheck = objCardBuss.CheckUserAuth(sPINInput,g_Card.GetPin());
                if (nCheck == VALID_PIN)
                {   
                    EndDialog(hWnd, 0);
                    MenuDlg menuDlg(hGlobalInst, hWnd);                   
                }
                else 
                {
                    if (nCheck == INVALID_PIN_LOCK)
                    {
                        MessageBox(hWnd, CARD_LOCKED_TMP, CARD_LOCKED_CAPTION, MB_ICONERROR);
                    }
                    else
                    {
                        MessageBox(hWnd, PIN_INVALID, PIN_INVALID_CAPTION, MB_ICONERROR);
                    }
                    EndDialog(hWnd, 0);  
                    CValidateCardDlg objValidCard(hGlobalInst, NULL);
                }
				return TRUE;
			}  
        case IDCANCEL:
            EndDialog(hWnd, 0);
            CValidateCardDlg objValidCard(hGlobalInst, NULL);
            return TRUE;
        }
        break;
    default:
        return FALSE;
    }
    return TRUE;
}

